package com.mayikt.service.impl;

import com.mayikt.base.BaseApiService;
import com.mayikt.base.BaseResponse;
import com.mayikt.mp.config.WxMpConfiguration;
import com.mayikt.mp.config.WxMpProperties;
import com.mayikt.request.ErrorTemplateDto;
import com.mayikt.service.WeiXinErrorTemplateService;
import com.mayikt.utils.SimpleDateFormatUtil;
import me.chanjar.weixin.mp.api.WxMpTemplateMsgService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
public class WeiXinErrorTemplateServiceImpl extends BaseApiService implements WeiXinErrorTemplateService {
    @Autowired
    private WxMpProperties wxMpProperties;

    @Override
    public BaseResponse<String> sendErrorTemplate(ErrorTemplateDto errorTemplateDto) {
        String serviceId = errorTemplateDto.getServiceId();
        if (StringUtils.isEmpty(serviceId)) {
            return setResultError("serviceId不能为空");
        }
        Date errorDate = errorTemplateDto.getErrorDate();
        if (errorDate == null) {
            return setResultError("errorDate不能为空");
        }
        String errorMsg = errorTemplateDto.getErrorMsg();
        if (StringUtils.isEmpty(errorMsg)) {
            return setResultError("errorMsg不能为空");
        }
        String openId = errorTemplateDto.getOpenId();
        if (StringUtils.isEmpty(openId)) {
            return setResultError("openId参数不能为空!");
        }
        String serverIp = errorTemplateDto.getServerIp();
        if (StringUtils.isEmpty(serverIp)) {
            return setResultError("serverIp参数不能为空!");
        }
        WxMpTemplateMessage wxMpTemplateMessage = new WxMpTemplateMessage();
        wxMpTemplateMessage.
                setTemplateId("0dz6fPAphJ6gtjjp9gtLfWvMgW4F8QDhsTBuoZMGGLY");
        wxMpTemplateMessage.setToUser(openId);
        List<WxMpTemplateData> data = new ArrayList<>();
        data.add(new WxMpTemplateData("first", serviceId));
        data.add(new WxMpTemplateData("keyword1",
                SimpleDateFormatUtil.getFormatStrByPatternAndDate(new Date())));
        data.add(new WxMpTemplateData("keyword2", serverIp));
        data.add(new WxMpTemplateData("keyword3", errorMsg));
        wxMpTemplateMessage.setUrl("http://www.mayikt.com");
        wxMpTemplateMessage.setData(data);
        try {
            String appId = wxMpProperties.getConfigs().get(0).getAppId();
            WxMpTemplateMsgService templateMsgService = WxMpConfiguration.getMpServices().get(appId).getTemplateMsgService();
            templateMsgService.sendTemplateMsg(wxMpTemplateMessage);
            return setResultSuccess();
        } catch (Exception e) {
            return setResultError("发送失败");
        }
    }
}